﻿
function ModuleStatus(data) {
    this.moduleName = data.ModuleName;
    this.serviceName = data.ServiceName;
    this.lastPulseMessage = data.LastPulseMessage;
    this.lastPulseUtc = data.LastPulseUtc;
    this.status = ko.observable(data.Status);

    this.lastPulseLocal = this.lastPulseUtc ? new Date(this.lastPulseUtc).toLocaleString() : '';
}

function StatusViewModel() {
    var self = this;

    self.moduleStatuses = ko.observableArray([]);

    self.startModule = function(moduleStatus) {
        console.log("start module");

        var index = self.moduleStatuses.indexOf(moduleStatus);
        
        $.ajax("/api/ModuleStatus/" + moduleStatus.moduleName + "/StartModule", {
            //data: ko.toJSON(moduleStatus.moduleName),
            type: "post", contentType: "application/json",
            success: function (result) {
                //self.moduleStatuses()[index] = new ModuleStatus(result);
                moduleStatus.status(result.Status);
            },
            error: function () {
                alert('Command failed');
            }
        });
    };
    
    self.stopModule = function (moduleStatus) {

        var index = self.moduleStatuses.indexOf(moduleStatus);
        
        $.ajax("/api/ModuleStatus/" + moduleStatus.moduleName + "/StopModule", {
            //data: ko.toJSON(moduleStatus.moduleName),
            type: "post", contentType: "application/json",
            success: function (result) {
                //self.moduleStatuses()[index] = new ModuleStatus(result);
                moduleStatus.status(result.Status);
            },
            error: function () {
                alert('Command failed');
            }
        });
    };
    
    $.getJSON("/api/ModuleStatus", function (allData) {
        console.log(allData);
        var mappedStatuses = $.map(allData, function (item) { return new ModuleStatus(item) });
        self.moduleStatuses(mappedStatuses);
        console.log(mappedStatuses);
    });
}

ko.applyBindings(new StatusViewModel());
